
import styled from 'styled-components';
import { useEffect, useRef, useState } from "react";
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
import * as Y from 'yjs';
// import { WebsocketProvider } from 'y-websocket';
import { MonacoBinding } from 'y-monaco';

export const SqlEditor = (props: { initValue?: string, onChange: (sql: string) => Promise<void> }) => {

    const [editor, setEditor] = useState<monaco.editor.IStandaloneCodeEditor | null>(null);

    const monacoEl = useRef(null);

    useEffect(() => {
        if (monacoEl) {
            setEditor((editor) => {
                if (editor) return editor;

                // const ydoc = new Y.Doc()
                // const provider = new WebsocketProvider(
                //   'wss://demos.yjs.dev/ws', // use the public ws server
                //   'monaco-demo',
                //   ydoc
                // )
                // const ytext = ydoc.getText('monaco')

                let e =  monaco.editor.create(monacoEl.current!, {
                    automaticLayout: true,
                    value: '',
                    language: 'sql'
                });
                // const monacoBinding = new MonacoBinding(ytext,  e.getModel()!, new Set([editor!]), provider.awareness)

                // provider.connect();

                return e;
            });
        }

        return () => editor?.dispose();
    }, [monacoEl.current]);


    return (
        <Container ref={monacoEl}></Container>
    );
};

export default SqlEditor;


const Container = styled.div`
    width: 100%;
    height: 100%;
`;